/**
 * DialogComponent.js
 * 
 * 通用对话框组件，支持标题、内容、按钮自定义。
 * 用于工具参数填写、工具结果详情展示等场景。
 */

(function() {
    'use strict';

    class DialogComponent {
        constructor(options = {}) {
            this.title = options.title || '对话框';
            this.content = options.content || '';
            this.buttons = options.buttons || [];
            this.onClose = options.onClose;
            this.width = options.width || 'auto';
            
            this.dialog = null;
            this.overlay = null;
        }

        /**
         * 显示对话框
         */
        show() {
            if (this.dialog) {
                this.close(); // 如果已存在，先关闭
            }

            // 创建遮罩层
            this.overlay = document.createElement('div');
            this.overlay.className = 'dialog-overlay';
            
            // 创建对话框容器
            this.dialog = document.createElement('div');
            this.dialog.className = 'dialog-container';
            if (this.width && this.width !== 'auto') {
                this.dialog.style.width = this.width;
            }

            // 创建对话框内容
            const headerDiv = document.createElement('div');
            headerDiv.className = 'dialog-header';
            
            const titleElement = document.createElement('h3');
            titleElement.className = 'dialog-title';
            titleElement.textContent = this.title;
            
            const closeBtn = document.createElement('button');
            closeBtn.className = 'dialog-close-btn';
            closeBtn.title = '关闭';
            closeBtn.innerHTML = '<span class="codicon codicon-close"></span>';
            
            headerDiv.appendChild(titleElement);
            headerDiv.appendChild(closeBtn);
            
            const bodyDiv = document.createElement('div');
            bodyDiv.className = 'dialog-body';
            bodyDiv.innerHTML = this.content;
            
            const footerDiv = document.createElement('div');
            footerDiv.className = 'dialog-footer';
            footerDiv.innerHTML = this._renderButtons();
            
            this.dialog.appendChild(headerDiv);
            this.dialog.appendChild(bodyDiv);
            this.dialog.appendChild(footerDiv);

            // 添加到页面
            document.body.appendChild(this.overlay);
            document.body.appendChild(this.dialog);

            // 绑定事件（在添加到DOM之后）
            this._bindEvents();

            // 动画显示
            requestAnimationFrame(() => {
                this.overlay.classList.add('show');
                this.dialog.classList.add('show');
            });
        }

        /**
         * 关闭对话框
         */
        close() {
            if (!this.dialog) return;

            // 动画隐藏
            this.overlay.classList.remove('show');
            this.dialog.classList.remove('show');

            // 等待动画完成后移除元素
            setTimeout(() => {
                if (this.overlay && this.overlay.parentNode) {
                    this.overlay.parentNode.removeChild(this.overlay);
                }
                if (this.dialog && this.dialog.parentNode) {
                    this.dialog.parentNode.removeChild(this.dialog);
                }
                this.overlay = null;
                this.dialog = null;

                // 移除 ESC 键监听
                if (this._escHandler) {
                    document.removeEventListener('keydown', this._escHandler);
                    this._escHandler = null;
                }

                // 触发关闭回调
                if (this.onClose) {
                    this.onClose();
                }
            }, 200); // 与CSS动画时间一致
        }

        /**
         * 更新对话框内容
         * @param {string} content - 新的内容HTML
         */
        updateContent(content) {
            if (!this.dialog) return;
            const body = this.dialog.querySelector('.dialog-body');
            if (body) {
                body.innerHTML = content;
            }
        }

        /**
         * 获取对话框DOM元素
         * @returns {HTMLElement|null}
         */
        getElement() {
            return this.dialog;
        }

        /**
         * 渲染按钮
         * @private
         */
        _renderButtons() {
            if (this.buttons.length === 0) {
                return '<vscode-button class="dialog-btn-close">关闭</vscode-button>';
            }

            return this.buttons.map(btn => {
                const appearance = btn.primary ? 'primary' : 'secondary';
                const className = btn.className || '';
                return `<vscode-button appearance="${appearance}" class="dialog-btn ${className}" data-action="${btn.action || ''}">${btn.text}</vscode-button>`;
            }).join('');
        }

        /**
         * 绑定事件
         * @private
         */
        _bindEvents() {
            if (!this.dialog) return;

            // 关闭按钮
            const closeBtn = this.dialog.querySelector('.dialog-close-btn');
            if (closeBtn) {
                closeBtn.onclick = () => this.close();
            }

            // 遮罩层点击关闭
            if (this.overlay) {
                this.overlay.onclick = () => this.close();
            }

            // 阻止对话框内部点击事件冒泡
            this.dialog.onclick = (e) => e.stopPropagation();

            // 按钮事件
            const buttons = this.dialog.querySelectorAll('.dialog-btn');
            buttons.forEach(btn => {
                btn.onclick = () => {
                    const action = btn.dataset.action;
                    
                    // 如果是关闭按钮或没有action，直接关闭
                    if (!action || btn.classList.contains('dialog-btn-close')) {
                        this.close();
                        return;
                    }

                    // 查找对应的按钮配置
                    const btnConfig = this.buttons.find(b => b.action === action);
                    if (btnConfig && btnConfig.onClick) {
                        const result = btnConfig.onClick(this);
                        // 如果回调返回false，不关闭对话框
                        if (result !== false) {
                            this.close();
                        }
                    }
                };
            });

            // ESC键关闭
            this._escHandler = (e) => {
                if (e.key === 'Escape') {
                    this.close();
                }
            };
            document.addEventListener('keydown', this._escHandler);
        }

        /**
         * 销毁对话框（移除事件监听）
         */
        destroy() {
            if (this._escHandler) {
                document.removeEventListener('keydown', this._escHandler);
            }
            this.close();
        }
    }

    window.DialogComponent = DialogComponent;
})();
